<template>
  <div class="category-page page-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <div class="list">
        <div class="home-icon">
          <i class="iconfont icon-home"></i>
        </div>
        <div class="item">
          <router-link to="/">
            <span class="text">首页</span>
          </router-link>
        </div>
        <div class="seperate">
          <i class="iconfont icon-arrow-right-thin"></i>
        </div>
        <div class="item">
          <span class="text">综合分类管理</span>
        </div>
      </div>
      <h1 class="page-title">综合分类管理</h1>
    </div>

    <!-- 分类类型切换 -->
    <div class="type-tabs">
      <div 
        class="tab-item"
        :class="{ active: activeType === 'window' }"
        @click="changeType('window')"
      >
        车窗膜分类
      </div>
      <div 
        class="tab-item"
        :class="{ active: activeType === 'paint' }"
        @click="changeType('paint')"
      >
        车漆膜分类
      </div>
      <div 
        class="tab-item"
        :class="{ active: activeType === 'building' }"
        @click="changeType('building')"
      >
        建筑家居膜分类
      </div>
    </div>

    <!-- 操作栏 -->
    <div class="action-bar">
      <button class="v-button primary" @click="showAddPopup">
        <i class="iconfont icon-add"></i> 添加分类
      </button>

      <!-- 搜索框 -->
      <div class="search-wrapper">
        <div class="search-input">
          <i class="iconfont icon-search"></i>
          <input
            v-model="searchQuery"
            placeholder="搜索分类名称"
            @keyup.enter="handleSearch"
          />
          <i
            v-if="searchQuery"
            class="iconfont icon-close"
            @click="handleSearchClear"
          ></i>
        </div>
      </div>
    </div>

    <!-- 分类表格 -->
    <div class="v-container">
      <table class="v-table">
        <thead>
          <tr>
            <th width="80">ID</th>
            <th>分类名称</th>
            <th>分类描述</th>
            <th width="180">创建时间</th>
            <th width="180">更新时间</th>
            <th width="200">操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="category in filteredCategoryList" :key="category.id">
            <td>{{ category.id }}</td>
            <td>{{ category.name }}</td>
            <td>{{ category.info }}</td>
            <td>{{ formatTimestamp(category.created_at) }}</td>
            <td>{{ formatTimestamp(category.updated_at) }}</td>
            <td>
              <div class="control">
                <button class="v-button" @click="showEditPopup(category)">
                  <i class="iconfont icon-edit"></i> 编辑
                </button>
                <button class="v-button danger" @click="confirmDelete(category)">
                  <i class="iconfont icon-delete1"></i> 删除
                </button>
              </div>
            </td>
          </tr>
          <tr v-if="!loading && categoryList.length === 0">
            <td colspan="6" class="empty-row">
              <i class="iconfont icon-empty"></i>
              {{ searchQuery ? "没有找到匹配的分类" : "暂无数据" }}
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 添加/编辑分类弹窗 -->
    <vPopup
      v-model="showCategoryPopup"
      :title="isEditMode ? '编辑分类' : '添加分类'"
      width="600px"
      @confirm="submitCategoryForm"
    >
      <div class="category-form">
        <div class="form-group">
          <label class="form-label">分类类型</label>
          <div class="type-radio-group">
            <label class="radio-item">
              <input 
                type="radio" 
                v-model="formData.type" 
                value="window"
                :disabled="isEditMode"
              >
              <span>车窗膜</span>
            </label>
            <label class="radio-item">
              <input 
                type="radio" 
                v-model="formData.type" 
                value="paint"
                :disabled="isEditMode"
              >
              <span>车漆膜</span>
            </label>
            <label class="radio-item">
              <input 
                type="radio" 
                v-model="formData.type" 
                value="building"
                :disabled="isEditMode"
              >
              <span>建筑家居膜</span>
            </label>
          </div>
        </div>
        <div class="form-group">
          <label class="form-label">分类名称</label>
          <input
            v-model="formData.name"
            type="text"
            class="form-input"
            placeholder="请输入分类名称"
            required
          />
        </div>
        <div class="form-group">
          <label class="form-label">分类描述</label>
          <textarea
            v-model="formData.info"
            class="form-input"
            placeholder="请输入分类描述"
            rows="4"
          ></textarea>
        </div>
      </div>
    </vPopup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { get, post } from "@/utils/request";
import { formatDate } from "@/utils/date";
import { vConfirm } from "@/plugins/vConfirm";
import { vToast } from "@/plugins/vToast";

const categoryList = ref([]);
const loading = ref(false);
const searchQuery = ref("");
const showCategoryPopup = ref(false);
const isEditMode = ref(false);
const activeType = ref('window'); // 当前激活的分类类型

// 表单数据
const formData = ref({
  id: null,
  type: "window",
  name: "",
  info: "",
});

// 切换分类类型
const changeType = (type) => {
  activeType.value = type;
  fetchCategories();
};

// 获取分类列表
const fetchCategories = async () => {
  try {
    loading.value = true;
    const res = await get("/filmCategory/list", { type: activeType.value });

    if (res.code === 200) {
      categoryList.value = res.data || [];
    } else {
      vToast.error(res.msg || "获取分类列表失败");
    }
  } catch (error) {
    vToast.error("获取分类列表失败");
    console.error(error);
  } finally {
    loading.value = false;
  }
};

// 格式化时间戳
const formatTimestamp = (timestamp) => {
  if (!timestamp) return "-";
  return formatDate(new Date(timestamp * 1000));
};

// 搜索
const handleSearch = () => {
  fetchCategories();
};

const handleSearchClear = () => {
  searchQuery.value = "";
  fetchCategories();
};

// 过滤后的分类列表
const filteredCategoryList = computed(() => {
  let list = [...categoryList.value];
  
  // 应用搜索条件
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase();
    list = list.filter(item => 
      item.name.toLowerCase().includes(query) || 
      (item.info && item.info.toLowerCase().includes(query))
    );
  }
  
  return list;
});

// 显示添加弹窗
const showAddPopup = () => {
  isEditMode.value = false;
  formData.value = {
    id: null,
    type: activeType.value,
    name: "",
    info: "",
  };
  showCategoryPopup.value = true;
};

// 显示编辑弹窗
const showEditPopup = (category) => {
  isEditMode.value = true;
  formData.value = {
    id: category.id,
    type: category.type,
    name: category.name,
    info: category.info,
  };
  showCategoryPopup.value = true;
};

// 提交分类表单
const submitCategoryForm = async () => {
  try {
    // 验证逻辑
    if (!formData.value.name) {
      vToast.warning("请输入分类名称");
      return;
    }

    const api = isEditMode.value ? "/filmCategory/update" : "/filmCategory/add";
    const res = await post(api, formData.value);

    if (res.code === 200) {
      vToast.success(isEditMode.value ? "分类更新成功" : "分类添加成功");
      fetchCategories(); // 刷新列表
      showCategoryPopup.value = false;
    } else {
      vToast.error(res.msg || "操作失败");
    }
  } catch (error) {
    vToast.error("提交失败");
    console.error(error);
  }
};

// 删除确认
const confirmDelete = (category) => {
  vConfirm({
    message: `确定要删除分类【${category.name}】吗？`,
    onConfirm: () => deleteCategory(category.id),
  });
};

const deleteCategory = async (id) => {
  try {
    const res = await post("/filmCategory/delete", { id });

    if (res.code === 200) {
      vToast.success("分类删除成功");
      fetchCategories();
    } else {
      vToast.error(res.msg || "删除失败");
    }
  } catch (error) {
    vToast.error("删除失败");
    console.error(error);
  }
};

// 初始化加载数据
onMounted(() => {
  fetchCategories();
});
</script>

<style scoped lang="less">
.category-page {
  .breadcrumb {
    margin-bottom: 20px;
    
    .list {
      display: flex;
      align-items: center;
      font-size: 14px;
      
      .home-icon {
        color: #999;
      }
      
      .item {
        margin-right: 8px;
        
        .text {
          color: #333;
          
          &:hover {
            color: var(--v-theme);
          }
        }
      }
      
      .seperate {
        margin-right: 8px;
        color: #999;
      }
    }
    
    .page-title {
      margin-top: 10px;
      font-size: 24px;
      font-weight: 500;
      color: #333;
    }
  }

  .type-tabs {
    display: flex;
    margin-bottom: 20px;
    border-bottom: 1px solid var(--v-border-color);
    
    .tab-item {
      padding: 10px 20px;
      cursor: pointer;
      font-size: 14px;
      color: var(--v-text);
      border-bottom: 2px solid transparent;
      transition: all 0.3s;
      
      &:hover {
        color: var(--v-theme);
      }
      
      &.active {
        color: var(--v-theme);
        border-bottom-color: var(--v-theme);
        font-weight: 500;
      }
    }
  }

  .action-bar {
    display: flex;
    align-items: center;
    margin-bottom: 20px;
    gap: 15px;

    .search-wrapper {
      flex: 1;
      max-width: 300px;
      margin-left: auto;

      .search-input {
        position: relative;
        display: flex;
        align-items: center;
        background: var(--v-card-bg);
        border-radius: var(--v-card-radius);
        border: 1px solid var(--v-border-color);
        padding: 0 10px;
        height: 36px;

        i {
          color: var(--v-text-light);
          margin-right: 8px;
        }

        input {
          flex: 1;
          border: none;
          background: transparent;
          outline: none;
          color: var(--v-text);

          &::placeholder {
            color: var(--v-text-light);
          }
        }

        .icon-close {
          cursor: pointer;
          margin-left: 8px;

          &:hover {
            color: var(--v-danger);
          }
        }
      }
    }
  }

  .v-container {
    background-color: var(--v-card-bg);
    border-radius: var(--v-card-radius);
    box-shadow: var(--v-shadow);
    padding: 20px;
    margin-top: 30px;
    transition: all 0.3s;
  }

  .v-table {
    width: 100%;
    border-collapse: collapse;
    font-size: 14px;

    th,
    td {
      padding: 12px 16px;
      text-align: left;
      border-bottom: 1px solid var(--v-border-color);
    }

    th {
      font-weight: bold;
      color: #333;
    }

    tr:hover {
      background-color: #f9f9f9;
    }
  }

  .control {
    display: flex;
    align-items: center;
    gap: 8px;

    .v-button {
      padding: 0px 8px;
      font-size: 12px;
      min-width: auto;
      height: 32px;
      line-height: 32px;
      background: var(--v-background-pure);
      color: var(--v-sidebar-background);
      border: var(--v-sidebar-background) 1px solid;

      i {
        margin-right: 4px;
      }

      &.danger {
        color: var(--v-danger);
        border-color: var(--v-danger);
      }
    }
  }

  .empty-row {
    text-align: center;
    padding: 20px;
    color: var(--v-text-light);

    .iconfont {
      font-size: 48px;
      margin-bottom: 10px;
      display: block;
    }
  }

  /* 分类表单样式 */
  .category-form {
    padding: 16px;

    .form-group {
      margin-bottom: 16px;

      .form-label {
        display: block;
        margin-bottom: 8px;
        font-size: 14px;
        color: #333;
        font-weight: 500;
      }

      .type-radio-group {
        display: flex;
        gap: 20px;
        
        .radio-item {
          display: flex;
          align-items: center;
          cursor: pointer;
          
          input {
            margin-right: 6px;
          }
          
          span {
            user-select: none;
          }
        }
      }

      .form-input {
        width: 100%;
        padding: 10px 12px;
        border: 1px solid #ddd;
        border-radius: 4px;
        font-size: 14px;
        transition: border-color 0.3s;
        
        &:focus {
          border-color: var(--v-theme);
          outline: none;
        }
        
        &[disabled] {
          background-color: #f5f5f5;
          cursor: not-allowed;
        }
      }

      textarea.form-input {
        min-height: 100px;
        resize: vertical;
      }
    }
  }
}
</style>